<template>
  <div class="book-manage-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar title="账本管理" 
    left-arrow @click-left="goBack" 
    :style="{ backgroundColor: '#FFD847' }" />

    <!-- 空状态区域 -->
    <div v-if="books.length === 0" class="empty-state">
      <van-empty description="暂时没有账本～" />
      <van-button class="create-book-btn" round color="#FFD814" text-color="#333" @click="showBottom = true">
        + 创建账本
      </van-button>
    </div>

    <!-- 账本列表区域（暂无数据时不显示） -->
    <div v-else class="book-list">
      <van-cell-group inset>
        <van-cell 
          v-for="book in books" 
          :key="book.id"
          :title="book.remark"
          :label="book.type"
          is-link
          @click="goToDetail(book)"
        >
          <template #icon>
            <van-icon :name="getBookIcon(book.categoryId)" class="book-icon" :style="{ color: getBookColor(book.categoryId) }" />
          </template>
          <template #value>
            <span class="book-money">¥{{ book.balance !== undefined ? book.balance.toFixed(2) : '0.00' }}</span>
          </template>
        </van-cell>
      </van-cell-group>
      
      <!-- 添加账本按钮 -->
      <van-button class="add-book-btn" round color="#FFD814" text-color="#333" @click="showBottom = true">
        + 创建新账本
      </van-button>
    </div>

    <!-- 底部圆角弹窗：选择账本模板 -->
    <van-popup v-model:show="showBottom" round position="bottom">
      <div class="popup-header">
        <van-button class="popup-cancel" type="text" @click="showBottom = false">
          取消
        </van-button>
        <div class="popup-title">选择账本模板</div>
        <div style="width: 44px;"></div> <!-- 占位元素，保持标题居中 -->
      </div>
      <div class="template-list">
        <van-grid :column-num="2" :gutter="16" clickable :border="false">
          <van-grid-item v-for="(item, index) in bookTemplates" :key="index" :text="item.name"
            @click="selectTemplate(item)">
            <template #icon>
              <div class="template-icon-wrapper">
                <van-icon :name="item.icon" size="24" :class="`template-icon ${item.type}-icon`" />
              </div>
            </template>
            <template #text>
              <span class="template-name">{{ item.name }}</span>
              <span class="template-desc">{{ item.desc }}</span>
            </template>
          </van-grid-item>
        </van-grid>
      </div>
    </van-popup>

    <!-- 输入账本名称弹窗 -->
    <van-popup v-model:show="showNameInput" round position="center" :style="{ width: '80%', padding: '20px' }">
      <div class="name-input-dialog">
        <h3>创建账本</h3>
        <p class="template-hint">模板：{{ selectedTemplate?.name }}</p>
        <van-field
          v-model="bookName"
          label="账本名称"
          placeholder="例如：我的生意账本"
          maxlength="20"
          show-word-limit
          autofocus
        />
        <div class="dialog-actions">
          <van-button block @click="cancelCreate">取消</van-button>
          <van-button block type="primary" @click="confirmCreate" :loading="creating">创建</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getAccountList, createAccount } from '@/api/index';
import { showToast, showDialog, showLoadingToast, closeToast } from 'vant';

const router = useRouter();
const books = ref([]); // 账本列表（初始为空）
const showBottom = ref(false); // 弹窗显示状态
const showNameInput = ref(false); // 名称输入弹窗
const loading = ref(false);
const creating = ref(false);
const bookName = ref('');
const selectedTemplate = ref(null);

// 账本模板数据（调整间距和布局，图标保持不变）
const bookTemplates = ref([
  {
    type: 'business',
    icon: 'shop-o', // 生意账本图标
    name: '生意账本',
    desc: '生意经营专用账本'
  },
  {
    type: 'expense',
    icon: 'gold-coin-o', // 报销账本图标
    name: '报销账本',
    desc: '适合记录报销账目'
  },
  {
    type: 'company',
    icon: 'bag-o', // 公司账本图标
    name: '公司账本',
    desc: '管理公司采购必备'
  },
  {
    type: 'team',
    icon: 'friends-o', // 团队账本图标
    name: '团队账本',
    desc: '班费/团建经费专属'
  },
  {
    type: 'wechat',
    icon: 'wap-home-o', // 微商账本图标
    name: '微商账本',
    desc: '代购卖货账目'
  },
  {
    type: 'custom',
    icon: 'edit', // 自定义账本图标
    name: '自定义账本',
    desc: '自定义你的专属账本'
  }
]);

// 返回上一页
const goBack = () => {
  router.back();
};

// 选择账本模板
const selectTemplate = (item) => {
  console.log('选择了模板：', item.name);
  selectedTemplate.value = item;
  bookName.value = '';
  showBottom.value = false;
  showNameInput.value = true;
};

// 取消创建
const cancelCreate = () => {
  showNameInput.value = false;
  bookName.value = '';
  selectedTemplate.value = null;
};

// 确认创建账本
const confirmCreate = async () => {
  if (!bookName.value.trim()) {
    showToast('请输入账本名称');
    return;
  }
  
  creating.value = true;
  
  try {
    const accountData = {
      categoryId: getCategoryIdByType(selectedTemplate.value.type),
      type: selectedTemplate.value.name,
      remark: bookName.value.trim()
    };
    
    console.log('创建账本数据:', accountData);
    const response = await createAccount(accountData);
    console.log('创建账本响应:', response);
    
    // 响应拦截器已经提取了 data，如果执行到这里说明创建成功
    showToast('创建成功');
    showNameInput.value = false;
    bookName.value = '';
    selectedTemplate.value = null;
    
    // 重新加载账本列表
    await loadAccountList();
  } catch (error) {
    console.error('创建账本失败:', error);
    showToast(error.message || '创建失败，请重试');
  } finally {
    creating.value = false;
  }
};

// 根据账本类型获取categoryId
const getCategoryIdByType = (type) => {
  const typeMap = {
    'business': 1,
    'expense': 2,
    'company': 3,
    'team': 4,
    'wechat': 5,
    'custom': 6
  };
  return typeMap[type] || 6;
};

// 加载账本列表
const loadAccountList = async () => {
  loading.value = true;
  try {
    const response = await getAccountList();
    console.log('获取账本列表响应:', response);
    
    // 响应拦截器已经提取了 data，直接使用即可
    if (Array.isArray(response)) {
      books.value = response;
      console.log('账本列表加载成功:', books.value.length, '个账本');
    } else {
      console.error('响应格式错误:', response);
      books.value = [];
      showToast('数据格式错误');
    }
  } catch (error) {
    console.error('加载账本列表失败:', error);
    showToast(error.message || '加载失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 根据categoryId获取图标
const getBookIcon = (categoryId) => {
  const iconMap = {
    1: 'shop-o',
    2: 'gold-coin-o',
    3: 'bag-o',
    4: 'friends-o',
    5: 'wap-home-o',
    6: 'edit'
  };
  return iconMap[categoryId] || 'edit';
};

// 根据categoryId获取颜色
const getBookColor = (categoryId) => {
  const colorMap = {
    1: '#07c160',
    2: '#ff976a',
    3: '#666',
    4: '#1989fa',
    5: '#07c160',
    6: '#ff976a'
  };
  return colorMap[categoryId] || '#666';
};

// 跳转到账本详情
const goToDetail = (book) => {
  router.push({
    path: '/ledger-details',
    query: { id: book.id }
  });
};

// 组件挂载时加载账本列表
onMounted(() => {
  loadAccountList();
});
</script>

<style scoped>
:deep(.van-nav-bar) {
  .van-nav-bar__arrow {
    color: #333;
    /* 箭头颜色 */
    font-size: 18px;
    /* 箭头大小 */
    font-weight: 600;
    /* 箭头粗细 */
  }
}
.book-manage-page {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.book-list {
  padding: 16px;
}

.book-icon {
  margin-right: 12px;
  font-size: 24px;
}

.book-money {
  font-weight: 600;
  color: #07c160;
}

.add-book-btn {
  margin-top: 20px;
  width: 100%;
}

.empty-state {
  padding: 50px 0;
  text-align: center;
}

.create-book-btn {
  margin-top: 20px;
  width: 200px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.popup-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.popup-cancel {
  background: none;
  border: none;
  padding: 0;
}

.template-list {
  padding: 16px;
  max-height: calc(100vh - 100px);
  overflow-y: auto;
}

.van-grid-item__content {
  flex-direction: column;
  align-items: flex-start;
  text-align: left;
  padding: 16px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 模板图标样式 */
.template-icon-wrapper {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12px;
  background-color: #f7f8fa;
}

.template-icon {
  font-size: 24px;
}

.business-icon {
  color: #07c160;
}

.expense-icon {
  color: #ff976a;
}

.company-icon {
  color: #666;
}

.team-icon {
  color: #1989fa;
}

.wechat-icon {
  color: #07c160;
}

.custom-icon {
  color: #ff976a;
}

.template-name {
  font-size: 16px;
  color: #333;
  margin-bottom: 4px;
}

.template-desc {
  font-size: 12px;
  color: #999;
}

/* 名称输入弹窗 */
.name-input-dialog {
  text-align: center;
}

.name-input-dialog h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
  color: #333;
}

.template-hint {
  margin: 0 0 20px 0;
  font-size: 14px;
  color: #666;
}

.dialog-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}
</style>